import { defineStore } from 'pinia'
import { onMounted, reactive, ref } from 'vue'
import { get, post } from '@/utils/api'
import { MessagePlugin } from 'tdesign-vue-next'

export const useAdminPayStore = defineStore('adminPay', () => {
  const showType = ref<string>('1')
  const wechatPayData = reactive({
    id: 1,
    merchantId: '',
    appid: '',
    apiV3Key: '',
    merchantSerialNumber: '',
    privateKey: '',
    status: 0
  })

  const saveConfig = async () => {
    try {
      loading.value = true
      const wechatPayResponse = await post('/api/wechatPay/saveConfig', wechatPayData)
      const aliPayResponse = await post('/api/aliPay/saveConfig', aliPayData)
      loading.value = false
      if (wechatPayResponse.status === 'success' && aliPayResponse.status === 'success') {
        MessagePlugin.closeAll()
        await MessagePlugin('success', '配置保存成功！')
      } else {
        MessagePlugin.closeAll()
        await MessagePlugin('error', '配置保存失败！')
      }
      await getWechatPayConfig()
      await getAliPayConfig()
    } catch (err) {
      console.log(err)
    }
  }

  const getWechatPayConfig = async () => {
    try {
      const response = await get('/api/wechatPay/getConfig')
      Object.assign(wechatPayData, response)
    } catch (err) {
      console.log(err)
    }
  }

  const getAliPayConfig = async () => {
    try {
      const response = await get('/api/aliPay/getConfig')
      Object.assign(aliPayData, response)
    } catch (err) {
      console.log(err)
    }
  }

  const aliPayData = reactive({
    id: 1,
    appid: '',
    publicKey: '',
    privateKey: '',
    status: 0
  })

  const loading = ref<boolean>(false)
  const contentLoading = ref<boolean>(true)
  onMounted(async () => {
    await getWechatPayConfig()
    await getAliPayConfig()
    contentLoading.value = false
  })

  return {
    wechatPayData,
    showType,
    saveConfig,
    aliPayData,
    loading,
    contentLoading
  }
})
